package br.ucb.sacop.webservice;

import java.util.ArrayList;
import java.util.List;

import android.util.Log;
import br.ucb.sacop.bean.Aluno;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;

public class ClientREST extends GenericREST{

	

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String URL = getUrlWs()+"aluno/";

	public Aluno getAluno(int id) throws Exception {

		String[] resposta = new WebServiceClient().get(URL + id);

		if (resposta[0].equals("200")) {
			Gson gson = new Gson();
			Aluno aluno = gson.fromJson(resposta[1], Aluno.class);
			return aluno;
		} else {
			throw new Exception(resposta[1]);
		}
	}

	public List<Aluno> getListaAluno() throws Exception {

		String[] resposta = new WebServiceClient().get(URL
				+ "buscarTodosGSON");

		if (resposta[0].equals("200")) {
			Gson gson = new Gson();
			ArrayList<Aluno> listaAluno = new ArrayList<Aluno>();
			JsonParser parser = new JsonParser();
			JsonArray array = parser.parse(resposta[1]).getAsJsonArray();

			for (int i = 0; i < array.size(); i++) {
				listaAluno.add(gson.fromJson(array.get(i), Aluno.class));
			}
			return listaAluno;
		} else {
			throw new Exception(resposta[1]);
		}
	}

	public String inserirAluno(Aluno aluno) throws Exception {
		
		Gson gson = new Gson();
		String clienteJSON = gson.toJson(aluno);
		String[] resposta = new WebServiceClient().post(URL + "inserir/",
				clienteJSON);
		Log.i("sacopTeste", resposta[0]);
		if (resposta[0].equals("200")) {
			return resposta[1];
		} else {
			throw new Exception(resposta[1]);
		}
	}
	
	public String atualizarAluno(Aluno aluno) throws Exception {
		Gson gson = new Gson();
		String clienteJSON = gson.toJson(aluno);
		String[] resposta = new WebServiceClient().post(URL + "update/",
				clienteJSON);
		Log.i("sacopTeste", resposta[0]);
		if (resposta[0].equals("200")) {
			return resposta[1];
		} else {
			throw new Exception(resposta[1]);
		}
	}

	public String deletarAluno(int id) {
		String[] resposta = new WebServiceClient().get(URL + "delete/" + id);
		return resposta[1];
	}

}
